/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <napi/native_api.h>
#include <napi/native_node_api.h>
#include <string>
#include "ReplayEncoder.h"

static ReplayEncoder g_encoder;

static napi_value Init(napi_env env, napi_callback_info info) {
    size_t argc = 5;
    napi_value argv[5];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    if (argc < 5) return nullptr;

    int32_t fd = 0, width = 0, height = 0, fps = 0;
    napi_get_value_int32(env, argv[0], &fd);
    napi_get_value_int32(env, argv[1], &width);
    napi_get_value_int32(env, argv[2], &height);
    napi_get_value_int32(env, argv[3], &fps);

    std::string mime;
    size_t len = 0; (void)len;
    napi_get_value_string_utf8(env, argv[4], nullptr, 0, &len);
    mime.resize(len);
    napi_get_value_string_utf8(env, argv[4], mime.data(), len + 1, &len);

    bool ok = g_encoder.Init(fd, width, height, fps, mime.c_str());
    napi_value ret; napi_get_boolean(env, ok, &ret);
    return ret;
}

static napi_value Encode(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    if (argc < 2) return nullptr;

    void* data = nullptr; size_t length = 0;
    napi_get_arraybuffer_info(env, argv[0], &data, &length);
    int64_t ts = 0; napi_get_value_int64(env, argv[1], &ts);
    bool ok = g_encoder.EncodeFrame((uint8_t*)data, length, ts);
    napi_value ret; napi_get_boolean(env, ok, &ret);
    return ret;
}

static napi_value Finalize(napi_env env, napi_callback_info info) {
    g_encoder.Finalize();
    napi_value ret; napi_get_undefined(env, &ret);
    return ret;
}

static napi_value Export(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"init", nullptr, Init, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"encode", nullptr, Encode, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"finalize", nullptr, Finalize, nullptr, nullptr, nullptr, napi_default, nullptr},
    };
    napi_define_properties(env, exports, sizeof(desc)/sizeof(desc[0]), desc);
    return exports;
}

extern "C" __attribute__((visibility("default"))) void NAPI_app_ability_Register(napi_env env, napi_value exports) {
    Export(env, exports);
}


